<template>
  <!-- 耗材物料主数据表表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="350"
    draggable
    @close="closeDialog"
    :close-on-click-modal="false"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="90">
      <el-row>
        <el-col :span="24">
          <el-form-item label="耗材编号" prop="materialCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.materialCode"
              placeholder="请输入耗材编号"
              clearable
            />

            <span v-else>{{ formData.materialCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="耗材名称" prop="materialName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.materialName"
              placeholder="请输入耗材名称"
              clearable
            />

            <span v-else>{{ formData.materialName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="物料组" prop="materialGroupId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.materialGroupId"
              placeholder="请选择物料组"
              clearable
              filterable
              @change="materialGroupChange"
              style="width: 100%"
            >
              <el-option
                v-for="item in mdmMatGroups"
                :key="item.id"
                :label="`${item.materialGroupCode}-${item.materialGroupName}`"
                :value="item.id"
              />
            </el-select>

            <span class="word" v-else
              >{{ formData.materialGroupCode }}-{{
                formData.materialGroupName
              }}</span
            >
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="包装容量" prop="childNum">
            <el-input-number
              v-if="!props.isReadonly"
              v-model="formData.childNum"
              placeholder="请输入包装容量"
              :min="1"
              :max="100"
              clearable
            />
            <span v-else>{{ formData.childNum }}</span>
          </el-form-item>
        </el-col>
        <!--<el-col :span="24">
          <el-form-item label="启用状态" prop="enabled">
            <el-radio-group v-model="formData.enabled" v-if="!props.isReadonly">
              <el-radio :label="'1'">启用</el-radio>
              <el-radio :label="'0'">停用</el-radio>
            </el-radio-group>

            <span v-else>{{ formData.enabled == "1" ? "启用" : "停用" }}</span>
          </el-form-item>
        </el-col>-->
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "EAMCSMMATERIALDATAADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  enabled: [],
  materialCode: [
    { required: true, message: "请输入耗材编号", trigger: "blur" },
  ],
  materialName: [
    { required: true, message: "请输入耗材名称", trigger: "blur" },
  ],
  materialGroupId: [
    { required: true, message: "请选择物料组", trigger: "change" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  enabled: "1",
  deleted: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  lastUpdateTime: "",
  materialName: "",
  materialCode: "",
  materialGroupId: "",
  materialGroupCode: "",
  materialGroupName: "",
  childNum: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        enabled,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdatedUserId,
        lastUpdatedUserName,
        lastUpdateTime,
        materialName,
        materialCode,
        materialGroupId,
        materialGroupCode,
        materialGroupName,
        childNum,
      } = newVal;
      Object.assign(formData, {
        id,
        enabled,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdatedUserId,
        lastUpdatedUserName,
        lastUpdateTime,
        materialName,
        materialCode,
        materialGroupId,
        materialGroupCode,
        materialGroupName,
        childNum,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.enabled = "1";
  formData.deleted = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.lastUpdateTime = "";
  formData.materialName = "";
  formData.materialCode = "";
  formData.materialGroupId = "";
  formData.materialGroupCode = "";
  formData.materialGroupName = "";
  formData.childNum = "";
}

const loading = ref(false);

/** 耗材物料主数据表保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/eam/csmmaterialdata/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
onMounted(() => {
  getMdmMatGroup();
});
const mdmMatGroups: any = ref([]);

const getMdmMatGroup = async () => {
  const res = await request({
    url: `/mdm/mdmmatgroup/getList`,
    method: "post",
    data: { enabled: "1" },
  });
  mdmMatGroups.value = res.data;
};
const materialGroup = ref("");
const materialGroupChange = (id: any) => {
  if (id) {
    mdmMatGroups.value.forEach((item: any) => {
      if (item.id == id) {
        materialGroup.value = item.materialGroupName;
        formData.materialGroupCode = item.materialGroupCode;
        formData.materialGroupName = item.materialGroupName;
        formData.childNum = item.childNum;
      }
    });
  } else {
    materialGroup.value = "";
    formData.materialGroupCode = "";
    formData.materialGroupName = "";
    formData.childNum = "";
  }
};
</script>
